package hos.thread

import android.os.Handler
import android.os.Looper

/**
 * <p>Title: MainHandler </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-08-06 10:46
 * @version : 1.0
 */
open class MainHandler protected constructor() : Handler(Looper.getMainLooper()) {
    fun postToMain(
        block: () -> Unit
    ): MainHandler {
        post {
            block()
        }
        return this
    }

    fun postOnMain(
        block: () -> Unit
    ): MainHandler {
        if (isMainThread()) {
            block()
            return this
        }
        post {
            block()
        }
        return this
    }

    fun clearCallback() {
        removeCallbacksAndMessages(null)
    }

    fun remove(runnable: Runnable) {
        removeCallbacks(runnable)
    }


    companion object {
        @JvmStatic
        val main by lazy {
            get()
        }

        @JvmStatic
        @Synchronized
        private fun get() = MainHandler()

        @JvmStatic
        fun isMainThread(): Boolean {
            return Looper.getMainLooper().thread === Thread.currentThread()
        }
    }
}